package com.yokead.controller.images;

import cn.jiangzeyin.DateUtil;
import cn.jiangzeyin.StringUtil;
import cn.jiangzeyin.common.JsonMessage;
import cn.jiangzeyin.pool.ThreadPoolService;
import cn.simplifydb.database.base.BaseRead;
import cn.simplifydb.database.run.read.SelectPage;
import com.alibaba.druid.util.JdbcUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.qiniu.common.QiniuException;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.model.FileInfo;
import com.yokead.common.QiNiuFile;
import com.yokead.common.QiNiuUtil;
import com.yokead.common.base.AdminBaseControl;
import com.yokead.database.DatabaseContextHolder;
import com.yokead.system.log.LogType;
import com.yokead.system.log.SystemLog;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletContext;
import javax.sql.DataSource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * Created by jiangzeyin on 2017/8/1.
 */
@Controller
@RequestMapping("images")
public class UploadLogController extends AdminBaseControl {


    private static boolean syncIng = false;

    @RequestMapping(value = "list.html", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String index() {
        String tip = sync();
        setAttribute("tip", tip);
        return "images/list";
    }

    @RequestMapping(value = "sync.json", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public String sync() {
        DataSource dataSource = DatabaseContextHolder.getDataSource();
        ServletContext application = getSession().getServletContext();
        boolean sync = Boolean.valueOf(StringUtil.convertNULL(application.getAttribute("sync")));
        if (sync) {
            return JsonMessage.getString(400, "上次没有没有同步结束");
        }
        if (syncIng) {
            return JsonMessage.getString(400, "上次没有没有同步结束:-1");
        }
        ThreadPoolService.newCachedThreadPool(UploadLogController.class).execute(() -> {
            syncIng = true;
            application.setAttribute("sync", true);
            try {
                BucketManager.FileListIterator fileListIterator;
                try {
                    BucketManager bucketManager = QiNiuFile.createImages();
                    //列举空间文件列表
                    fileListIterator = bucketManager.createFileListIterator(QiNiuUtil.getImagesBucket(), "", 50, null);
                } catch (IOException e) {
                    SystemLog.LOG(LogType.CONTROL_ERROR).error("获取错误", e);
                    return;
                }
                while (fileListIterator.hasNext()) {
                    //处理获取的file list结果
                    FileInfo[] items = fileListIterator.next();
                    in:
                    for (FileInfo item : items) {
                        // 判断是否存在
                        String eSql = "select ukey from uploadLog where ukey=?";
                        String key = item.key;
                        try {
                            List<Map<String, Object>> list = JdbcUtils.executeQuery(dataSource, eSql, key);
                            if (list != null && list.size() > 0) {
                                for (Map<String, Object> item_ : list) {
                                    String oldKey = StringUtil.convertNULL(item_.get("ukey"));
                                    if (oldKey.equals(key)) {
                                        continue in;
                                    }
                                }
                            }
                        } catch (SQLException e) {
                            SystemLog.LOG(LogType.CONTROL_ERROR).error("同步失败", e);
                            continue;
                        }
                        String sql = "insert into uploadLog(ukey,createTime,mimeType) values(?,?,?)";
                        List<Object> parameters = new ArrayList<>();
                        parameters.add(item.key);
                        parameters.add(item.putTime / 10000000L);
                        parameters.add(item.mimeType);
                        try {
                            JdbcUtils.execute(dataSource, sql, parameters);
                        } catch (SQLException e) {
                            SystemLog.LOG(LogType.CONTROL_ERROR).error("同步失败", e);
                        }
                    }
                }
            } finally {
                application.setAttribute("sync", false);
                syncIng = false;
            }
        });
        return JsonMessage.getString(200, "");
    }

    @RequestMapping(value = "list.json", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public String list(String pageNo, String type, String date) {
        int type_ = StringUtil.parseInt(type, 0);
        int startTime_int = 0;
        int endTime_int = 0;
        if (!StringUtil.isEmpty(date)) {
            String[] dates = StringUtil.stringToArray(date, "_");
            if (dates == null || dates.length < 2) {
                return JsonMessage.getString(103, "时间选择不正确");
            }
            try {
                startTime_int = (int) (DateUtil.parseTime(dates[0], "yyyy-MM-dd").getTime() / 1000L);
                endTime_int = (int) ((int) (DateUtil.parseTime(dates[1], "yyyy-MM-dd").getTime() / 1000L) + TimeUnit.HOURS.toSeconds(24));

                // page.setWhereWord("createTime>=" + startTime + " and createTime<=" + endTime);
            } catch (Exception e) {
                SystemLog.ERROR().error("时间格式不正确:" + date, e);
                return JsonMessage.getString(103, "时间格式不正确");
            }
        }

//        if (!StringUtil.isEmpty(endTime)) {
//            endTime += " 23:59:59";
//            endTime_int = DateUtil.formatTime(null, endTime);
//            if (endTime_int <= 0)
//                return JsonMessage.getString(140, "结束时间不正确：" + endTime);
//        }
        return doSelect(pageNo, 50 + "", type_, startTime_int, endTime_int);
    }

    @RequestMapping(value = "del.json", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public String del(String url) {
        url = StringUtil.convertNULL(url);
        if (!url.contains("://")) {
            return JsonMessage.getString(400, "删除失败,地址错误");
        }
        url = url.substring(url.indexOf("://") + 3);
        if (!url.contains("/")) {
            return JsonMessage.getString(400, "删除失败,地址错误2");
        }
        url = url.substring(url.indexOf("/") + 1);
        // 删除数据库
        DataSource dataSource = DatabaseContextHolder.getDataSource();
        String eSql = "delete from uploadLog where ukey=?";
        try {
            JdbcUtils.execute(dataSource, eSql, url);
        } catch (SQLException e) {
            SystemLog.LOG(LogType.CONTROL_ERROR).error("删除失败", e);
            return JsonMessage.getString(500, "删除数据失败");
        }
        // 删除远程文件
        try {
            BucketManager bucketManager = QiNiuFile.createImages();
            try {
                bucketManager.delete(QiNiuUtil.getImagesBucket(), url);
            } catch (QiniuException ex) {
                SystemLog.LOG(LogType.CONTROL_ERROR).error("删除失败", ex);
                return JsonMessage.getString(500, "删除失败：" + ex.response.toString());
            }
        } catch (IOException e) {
            SystemLog.LOG(LogType.CONTROL_ERROR).error("创建对象错误", e);
            return JsonMessage.getString(400, "删除异常");
        }
        return JsonMessage.getString(200, "删除成功");
    }

    private String doSelect(String pageNo, String pageSize, int type, int startTime, int endTIme) {
        int pageNo_int = StringUtil.parseInt(pageNo, 1);
        int pageSize_int = StringUtil.parseInt(pageSize, 10);
        SelectPage<?> selectPage = new SelectPage<>();
        selectPage.setSql("select uKey,createTime,mimeType from uploadLog");
        selectPage.setPageNoAndSize(pageNo_int, pageSize_int);
        if (type == 0) {
            selectPage.where("mimeType like 'image%'");
        } else {
            selectPage.where("mimeType not like 'image%'");
//            page.setPageSize(10);
        }
        if (startTime > 0) {
            selectPage.whereAnd("createTime>=" + startTime);
        }
        if (endTIme > 0) {
            selectPage.whereAnd("createTime<=" + endTIme);
        }
        selectPage.orderBy("createTime desc");
        selectPage.setTag("core");
        selectPage.setResultType(BaseRead.Result.PageResultType);

//        try {
//            SqlUtil.doPage(page);
//        } catch (SQLException e) {
//            SystemLog.ERROR().error("分页错误", e);
//            return JsonMessage.getString(500, "系统异常");
//        }
        JSONObject result = selectPage.run();
        if (result == null) {
            return JsonMessage.getString(404, "没有数据");
        }
        String doMain = QiNiuUtil.getDoMain();
        result.put("domain", doMain);
        //result.put("pageNo", page.getPageNo());
        //result.put("pageSize", page.getPageSize());
        //result.put("totalPage", page.getTotalPage());
        //result.put("totalRecord", page.getTotalRecord());
        JSONArray dataResults = result.getJSONArray("results");
        if (dataResults != null) {
            if (type != 0) {
                dataResults.forEach(o -> {
                    JSONObject jsonObject = (JSONObject) o;
                    String url = doMain + "/" + jsonObject.getString("uKey");
                    try {
                        jsonObject.put("context", getHtmlContent(url, "utf-8"));
                    } catch (Exception e) {
                        SystemLog.LOG(LogType.CONTROL_ERROR).error("获取异常", e);
                        jsonObject.put("context", "获取异常：" + e.getMessage());
                    }
                });
                result.put("results", dataResults);
            }
//            else {
//                result.put("results", page.getMapList());
//            }
        }
        return JsonMessage.getString(200, "获取成功", result);
    }

    /**
     * @param url_
     * @param encode
     * @return
     * @throws IOException
     * @author jiangzeyin
     * @date 2016-12-2
     */
    private static String getHtmlContent(String url_, String encode) throws IOException {
        StringBuilder contentBuffer = new StringBuilder();
        int responseCode = -1;
        HttpURLConnection con;
        URL url = new URL(url_);
        con = (HttpURLConnection) url.openConnection();
        // IE代理进行下载
        con.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
        con.setConnectTimeout(60000);
        con.setReadTimeout(60000);
        con.setInstanceFollowRedirects(true);
        // 获得网页返回信息码
        responseCode = con.getResponseCode();
        if (responseCode == 302) {
            String l = con.getHeaderField("Location");
            return getHtmlContent(l, encode);
        }
        if (responseCode == -1) {
            con.disconnect();
            return null;
        }
        // 请求失败
        if (responseCode >= 400) {
            con.disconnect();
            return null;
        }
        InputStream inStr = con.getInputStream();
        InputStreamReader istreamReader = new InputStreamReader(inStr, encode);
        BufferedReader buffStr = new BufferedReader(istreamReader);
        String str;
        while ((str = buffStr.readLine()) != null) {
            contentBuffer.append(str);
        }
        inStr.close();
        con.disconnect();
        return contentBuffer.toString();
    }
}
